package com.jw.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jw.handler.BusinessException;
import com.jw.response.ResultCode;
import com.jw.system.entity.Dept;
import com.jw.system.entity.Role;
import com.jw.system.entity.User;
import com.jw.system.entity.vo.UserVO;
import com.jw.system.mapper.DeptMapper;
import com.jw.system.mapper.RoleMapper;
import com.jw.system.mapper.UserMapper;
import com.jw.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author jw
 * @since 2021-04-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private RoleMapper roleMapper;


    /**
     * 分页+条件查询用户信息
     */
    @Override
    public Page<UserVO> getUserList(Integer current, Integer size, UserVO userVO) {
//        List<User> userList = userMapper.getUserList(page, userVO);
//        userMapper.p
        //返回用户集合
//        return page.setRecords(userList);
        Page<User> page = new Page<>(current, size);
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        if (userVO.getUsername() != null && !"".equals(userVO.getUsername())) {
            queryWrapper.like("username", userVO.getUsername());
        }
        if (userVO.getPhone() != null && !"".equals(userVO.getPhone())) {
            queryWrapper.like("phone", userVO.getPhone());
        }
        if (userVO.getEmail() != null && !"".equals(userVO.getEmail())) {
            queryWrapper.like("email", userVO.getEmail());
        }
        if (userVO.getSex() != null) {
            queryWrapper.like("sex", userVO.getSex());
        }
        if (userVO.getDeptId() != null) {
            queryWrapper.like("dept_id", userVO.getDeptId());
        }
        queryWrapper.ne("role_id",1);
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);

        List<User> users = userPage.getRecords();

        List<UserVO> userVOS = new ArrayList<>();
        for (User user : users) {
            UserVO userVO1 = new UserVO();
            BeanUtils.copyProperties(user, userVO1);
            if (user.getDeptId() != 0) {
                Dept dept = deptMapper.selectById(user.getDeptId());
                userVO1.setDeptName(dept.getName());
            } else {
                userVO1.setDeptName("无");
            }
            //规范生日格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            userVO1.setBirth(sdf.format(user.getBirth()));
            Role role = roleMapper.selectById(user.getRoleId());
            userVO1.setRoleName(role.getName());
            userVOS.add(userVO1);
        }
        Page<UserVO> userVOPage = new Page<>();
        userVOPage.setRecords(userVOS);
        userVOPage.setTotal(userPage.getTotal());
        System.out.println("===========================");
        System.out.println(userVOS);
        System.out.println("===========================");
        return userVOPage;
    }

    @Override
    public UserVO getUserInfo() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = null;
        UserVO userVO = new UserVO();
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        BeanUtils.copyProperties(user, userVO);
        if (user.getDeptId() != 0) {
            Dept dept = deptMapper.selectById(user.getDeptId());
            userVO.setDeptName(dept.getName());
        } else {
            userVO.setDeptName("无");
        }
        Role role = roleMapper.selectById(user.getRoleId());
        userVO.setRoleName(role.getName());
        return userVO;
    }

    @Override
    public void addUser(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        if (userMapper.selectCount(wrapper) != 0) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        user.setAvatar("http://pic.gerenjianli.com/xiaohui2046/b927.jpg");
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        Role role = roleMapper.selectById(user.getRoleId());
        user.setDeptId(role.getDeptId());
        userMapper.insert(user);
    }

    @Override
    public List<User> getAuditorsList(Long roleId) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getRoleId,roleId);
        List<User> users = userMapper.selectList(wrapper);
        return users;
    }

}
